package com.fingard.dsp.bank.directbank.sr11;

import java.io.File;
import java.io.IOException;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;

public class SR11Base extends DirectBase {
	/**
	 * 获取字符编码
	 * 
	 * @return 当前字符编码
	 */
	protected String getCharset() {
		return getBankConfig().getCharset("utf-8");
	}
	
	protected int getBatSeqNo(String p_reqDir) {
		int batSeqNo = -1;
		File refundFileDir = new File(p_reqDir);
		if (refundFileDir.exists()) {
			File[] refundFileList = refundFileDir.listFiles();
			if (refundFileList != null) {
				int total = 0;
				for(File refundFile : refundFileList) {
					if (!refundFile.getName().endsWith("zip")) {
						total++;
					}
				}
				batSeqNo = total + 1;
			}
		} else {
			batSeqNo = 1;
		}
		
		return batSeqNo;
	}
	
	public String sendPostJsonRequest(String json) {
		WriteBankUrlLogLn(bankFront.serverURL);
        WriteBankLogStep2(json);
        
	       PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
	        CloseableHttpClient httpClient = null;
	        connectionManager.setMaxTotal(1000);
	        connectionManager.setDefaultMaxPerRoute(200);
	        if (httpClient == null) {
	            RequestConfig requestConfig = RequestConfig.custom()
	                    .setConnectTimeout(600000)
	                    .setConnectionRequestTimeout(10000)
	                    .setSocketTimeout(600000)
	                    .build();
	            httpClient = HttpClients.custom()
	                    .setDefaultRequestConfig(requestConfig)
	                    .setConnectionManager(connectionManager)
	                    .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
	                    .build();
	        }
	        HttpPost httpPost = new HttpPost(bankFront.serverURL);
	        httpPost.addHeader("Content-Type", "application/json");
	        CloseableHttpResponse response = null;
	        StringEntity stringEntity = new StringEntity(json, getCharset());
	        stringEntity.setContentType("text/json");
	        stringEntity.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
	        try {
	            httpPost.setEntity(stringEntity);
	            response = httpClient.execute(httpPost);
	        } catch (IOException e1) {
	            e1.printStackTrace();
	        }
	        int status = response.getStatusLine().getStatusCode();
	        String result = null;
	        try {
	            if (200 == status) {
	                result = EntityUtils.toString(response.getEntity(), getCharset());
	                EntityUtils.consume(response.getEntity());
	            } else {
	                //logger.error("访问地址url[{}]状态码status[{}]", url, status);
	                System.out.println("url:"+bankFront.serverURL);
	                System.out.println("status:"+status);
	            }
	            response.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            httpPost.releaseConnection();
	        }
	        WriteBankLogStep3(result);
	        return result;
	    }
	
	protected String[] sendToBank(String sendMsg) throws Exception {
        String[] retStr;
        WriteBankUrlLogLn(bankFront.serverURL);
        WriteBankLogStep2(sendMsg);
        WebRequest tmpWebRequest = new WebRequest(bankFront.serverURL);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("connection", "Close");
        byte[] tmpUpBytes = sendMsg.getBytes(getCharset());
        retStr = tmpWebRequest.upload(tmpUpBytes, "UTF-8");
        WriteBankLogStep3(retStr[1]);
        if (retStr[0].length() == 0) {
            int tmpIndex = retStr[1].indexOf("{");
            if (tmpIndex > 0) {
                retStr[1] = retStr[1].substring(tmpIndex);
            }
        } else {
            this.WriteBankLogLn(tmpWebRequest.sbLog);
        }
        return retStr;
    }
	
}
